package com.xueliman.iov.server.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSONObject;
import com.xueliman.iov.cloud.framework.web.vo.SingleResultBundle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    //这个只是我这边的定义
    public static final int STATUS = 606;

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException ex) throws Exception {
        String errorMessage = "请稍后再试";
        if (ex instanceof FlowException) {
            log.debug("限流: ", ex);
        } else if (ex instanceof DegradeException) {
            log.debug("降级", ex);
        } else if (ex instanceof ParamFlowException) {
            log.debug("热点参数限流", ex);
        } else if (ex instanceof SystemBlockException) {
            log.debug("系统规则(负载/...不满足要求)", ex);
        } else if (ex instanceof AuthorityException) {
            log.debug("授权规则不通过", ex);
        }
        // http状态码
        response.setStatus(STATUS);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(SingleResultBundle.failed(errorMessage)));
    }
}
